package configuration;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Locale;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 获取spring中的bean
 *
 * @author wxf
 */
public class SpringContextUtil implements ApplicationContextAware {
	private static ApplicationContext context = null;
	public static final ObjectMapper mapper = new ObjectMapper();

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		context = applicationContext;
	}

	public static <T> T getBean(String beanName) {
		return (T) context.getBean(beanName);
	}

	public static <T> T getBean(Class clazz) {
		return (T) context.getBean(clazz);
	}

	public static String getMessage(String key) {
		return context.getMessage(key, null, Locale.getDefault());
	}

	/**
	 * json转换为对象
	 */
	public static <T> T getValue(String value, Type type) {
		if (String.class.getName().equals(type.getTypeName())) {
			return (T) value;
		}
		JavaType javaType = getCollectionType(type);
		try {
			return mapper.readValue(value, javaType);
		} catch (IOException e) {
				e.printStackTrace();
			try {
				return mapper.readValue("{\"state\":\"Failure\",\"message\":\"返回结果格式不正确\",\"data\":null}", javaType);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 组装新类型
	 */
	public static JavaType getCollectionType(Type type) {
		// 忽略空子段
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		return mapper.getTypeFactory().constructType(type);
	}
}
